package middleware

import (
	"2211a_mayi/api/internal/types"
	"context"
	jwt "github.com/golangblogs/gojwt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type AuthTokenMiddleware struct {
}

func NewAuthTokenMiddleware() *AuthTokenMiddleware {
	return &AuthTokenMiddleware{}
}

func (m *AuthTokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		token := r.Header.Get("token")
		if token == "" {
			resp := types.Response{
				Code: 10001,
				Msg:  "token为空",
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}

		// 验证token是否正确
		j := jwt.NewJWT("2211a_mayi")
		claims, err := j.ParseToken(token)
		if err != nil {
			resp := types.Response{
				Code: 10002,
				Msg:  "token不正确",
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		// 将claims中的信息写入上下文
		//next(w, r)
		// 把userId 存到context中
		ctx := context.WithValue(r.Context(), "userId", claims.ID)
		next(w, r.WithContext(ctx))
	}
}
